package com.jiangyg.mall.authz.support.authentication;

import com.jiangyg.mall.core.support.env.EnvConstant;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类描述：请求 authentication 匹配器
 * <p>只匹配 authentication 请求并排除指定参数</p>
 *
 * @author jiangyg
 * @date 2022-09-04
 */
public class AuthenticationRequestMatcher implements RequestMatcher {

    /**
     * 请求地址匹配器，此过滤器只处理此请求
     */
    private final AntPathRequestMatcher matcher = new AntPathRequestMatcher("/authentication");

    /**
     * 不鉴权的路径匹配集合
     */
    private final List<String> permitPathList;

    public AuthenticationRequestMatcher() {
        // TODO 考虑动态刷新
        final String[] permitPaths = EnvConstant.getStrings("security.permitPaths");
        permitPathList = Collections.unmodifiableList(Arrays.stream(permitPaths).collect(Collectors.toList()));
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        // 1. 如果非 authentication 请求，则直接跳过
        if (!matcher.matches(request)) {
            return false;
        }
        // 2. 不鉴权的路径也跳过
        final String path = request.getParameter("path");
        return !permitPathList.contains(path);
    }

}
